package com.dream.myqiyi.ui;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.dream.myqiyi.AsyncImageLoader.ImageCallback;
import com.dream.myqiyi.Global;
import com.dream.myqiyi.R;
import com.dream.myqiyi.dao.NoteModel;
import com.dream.myqiyi.service.ApplicationContext;
import com.dream.myqiyi.service.NoteService;
import com.dream.myqiyi.service.NotebookService;
import com.dream.myqiyi.service.TagService;
import com.dream.myqiyi.util.StringUtils;
import com.dream.myqiyi.widget.SosUniversalAdapter;
import com.dream.myqiyi.widget.SosUniversalListView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class NoteListActivity extends Activity {

	public final static int ALL_NOTE_TYPE = 0;
	public final static int NOTEBOOK_TYPE = 1;
	public final static int TAG_NOTE_TYPE = 2;
	public final static int FAVORITE_TYPE = 3;
	public final static int MAIN_TYPE = 4;
	
	public final static int NOTE_SORT_UPDATED = 0;
	public final static int NOTE_SORT_CREATE = 1;
	public final static int NOTE_SORT_TITLE = 2;
	

//	private boolean isGridView = false;
	private boolean isEditable = false;
	private int noteSortType = NOTE_SORT_UPDATED;
	
//	private View loadMoreView;
//	private Button loadmore_btn;

	private List<Item> listData = new ArrayList<Item>();
	private Map<String, ArrayList<Item>> listDataCate = new HashMap<String, ArrayList<Item>>();
	private Set<String> selectData = new HashSet<String>();
	
	ArrayList<Pair<String, ArrayList<Item>>> orderData = new ArrayList<Pair<String, ArrayList<Item>>>();

	private int noteType;
	private String notebookGuid;
	private String tagGuid;
	
	private ImageView mMenu = null;
	private TextView mTitle = null;
	private TextView mNoteCount = null;
	//private PinnedHeaderListView mDisplay = null;
	//private PinnedCategoryAdapter mCategoryAdapter = null;
	SosUniversalListView mDisplay;  //Diy ListView
	SectionComposerAdapter mCategoryAdapter;   //适配器

	private int pageSize=10;					//分页加载的数据的数量

	private RelativeLayout mViewBottom = null;
	
	private LinearLayout mEditBottom = null;
	
	private PopMenu popMenuNoteView;
	private PopMenu popMenuNoteSort;
	private PopMenu popMenuNoteMore;
	
	private static final int DIALOG_DELETE = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main_tab_notes);

		initUI();

		initUIData();
		
		//doUpdate(); 
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		doUpdate();
	}
	
 	private void initUI() {
		// top
		mMenu = (ImageView) findViewById(R.id.title_menu);
		mMenu.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//OpenDesktoop();
				Intent intent;
				switch (noteType) {
				case NOTEBOOK_TYPE:
					intent = new Intent(NoteListActivity.this, NotebookListActivity.class);
					break;
				case TAG_NOTE_TYPE:
					intent = new Intent(NoteListActivity.this, TagListActivity.class);
					break;
				default:
					intent = new Intent(NoteListActivity.this, MainActivity.class);
					break;
				}

				startActivity(intent);
				NoteListActivity.this.finish();
			}
		});
		mTitle = (TextView) findViewById(R.id.notes_title_tv);
		mNoteCount = (TextView) findViewById(R.id.notes_count_tv);

		// mid
		updateLayoutModel();
		
		// bottom
		updateBottomLayout();
	}
	
	private void updateBottomLayout() {
		if (mViewBottom == null) {
			mViewBottom = (RelativeLayout)findViewById(R.id.bottom_view_layout);
			findViewById(R.id.menu_new_ib).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// 切换到NoteViewActivity
					Bundle bundle = new Bundle();
					bundle.putInt("note_type", noteType);
					switch (noteType) {
					case NOTEBOOK_TYPE:
						bundle.putString("guid", notebookGuid);
						break;
					case TAG_NOTE_TYPE:
						bundle.putString("guid", tagGuid);
						break;
					}
					Intent intent = new Intent(NoteListActivity.this, NoteViewActivity.class);
					intent.putExtras(bundle);
	
					startActivity(intent);
					NoteListActivity.this.finish();
				}
	
			});
	
			findViewById(R.id.menu_view_ib).setOnClickListener(new OnClickListener() {
	
				@Override
				public void onClick(View v) {
					popMenuNoteView.showAtLocation(v, Gravity.BOTTOM, 0, 90);
				}
				
			});
	
			findViewById(R.id.menu_sort_ib).setOnClickListener(new OnClickListener() {
	
				@Override
				public void onClick(View v) {
					popMenuNoteSort.showAtLocation(v, Gravity.BOTTOM, 0, 90);
				}
				
			});
	
			findViewById(R.id.menu_search_ib).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// 切换到NotebookViewActivity
					Intent intent = new Intent(NoteListActivity.this, NoteSearchActivity.class);
					startActivity(intent);
					NoteListActivity.this.finish();
				}
			});
	
			findViewById(R.id.menu_more_ib).setOnClickListener(new OnClickListener() {
	
				@Override
				public void onClick(View v) {
					popMenuNoteMore.showAtLocation(v, Gravity.BOTTOM, 0, 90);
				}
				
			});
	
			popMenuNoteView = new PopMenu(NoteListActivity.this);
			popMenuNoteView.addItems(new String[] { "列表显示", "图形显示" });
			popMenuNoteView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					switch (position) {
					case 0:
						//isGridView = false;
						break;
					case 1:
						// TODO
						//isGridView = false;
						break;
					}
	
					// 更新列表模式
					updateAdapter();

					popMenuNoteView.dismiss();
				}
			});
	
			popMenuNoteSort = new PopMenu(NoteListActivity.this);
			popMenuNoteSort.addItems(new String[] { "按更新时间排序", "按创建时间排序", "按标题排序" });
			popMenuNoteSort.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					switch (position) {
					case 0:
						noteSortType = NOTE_SORT_UPDATED;
						break;
					case 1:
						noteSortType = NOTE_SORT_CREATE;
						break;
					case 2:
						noteSortType = NOTE_SORT_TITLE;
						break;
					}
					// 更新列表模式
					sortData();
					updateAdapter();

					popMenuNoteSort.dismiss();
				}
			});
	
			popMenuNoteMore = new PopMenu(NoteListActivity.this);
			popMenuNoteMore.addItems(new String[] { "删除笔记" });
			popMenuNoteMore.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					switch (position) {
					case 0:
						isEditable = true;
						// 更新列表模式
						updateAdapter();
						// 更新底部菜单
						updateBottomLayout();

						break;
					}
					popMenuNoteMore.dismiss();
				}
			});
		}

		if (mEditBottom == null) {
			mEditBottom = (LinearLayout)findViewById(R.id.bottom_edit_layout);
			this.findViewById(R.id.delete).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					new AlertDialog.Builder(NoteListActivity.this)
						.setTitle("提示")
						.setMessage("确认删除？")
						.setNegativeButton("取消", new DialogInterface.OnClickListener() {  
							public void onClick(DialogInterface dialog, int which) {
					 		}
						})  
						.setPositiveButton("确定", new DialogInterface.OnClickListener() {  
							public void onClick(DialogInterface dialog, int whichButton) {
								new DelNotesTask().execute("");
							}  
						})
						.show();  
				}
			});
			this.findViewById(R.id.selectall).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					for(int i=0;i<listData.size();i++){
						listData.get(i).b = true;
					}
					updateAdapter();
				}
				
			});
			this.findViewById(R.id.inverseselect).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					for(int i=0;i<listData.size();i++){
						Item item = listData.get(i);
						item.b = !item.b;//取反
					}
					updateAdapter();
				}
				
			});
			this.findViewById(R.id.cancel).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					for(int i=0;i<listData.size();i++){
						Item item = listData.get(i);
						item.b = !item.b;//取反
					}
					
					isEditable = false;
					// 更新列表模式
					updateAdapter();
					// 更新底部菜单
					updateBottomLayout();

				}
				
			});
			
		}
		
		if (isEditable) {
			mEditBottom.setVisibility(View.VISIBLE);
			mViewBottom.setVisibility(View.GONE);
		} else {
			mEditBottom.setVisibility(View.GONE);
			mViewBottom.setVisibility(View.VISIBLE);
		}
	}
	
	private void updateLayoutModel() {        	
        if (mDisplay == null) {
        	mDisplay = (SosUniversalListView) findViewById(R.id.lv_all_notes);
        	mDisplay.setPinnedHeaderView(LayoutInflater.from(this).inflate(R.layout.list_note_title, mDisplay, false));
        	mDisplay.setAdapter(mCategoryAdapter = new SectionComposerAdapter());

        	
    		mDisplay.setOnItemClickListener(new OnItemClickListener() {
    			@Override
    			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    				Item item = (Item)mCategoryAdapter.getItem(position);
    				if (item == null) {
    					return ;
    				}
    				if (isEditable) {
    					item.b = !item.b;//取反
    					updateAdapter();    					
    				} else {
	    				//从适配器中获取当前点击项的内容
	    				NoteModel note = item.note;
	
	    				Bundle bundle = new Bundle();
	    				bundle.putString("parent_ui", "note_list");
	    				bundle.putString("note_guid", note.getGuid());
	
	    				Intent intent = new Intent(NoteListActivity.this, NoteViewActivity.class);
	    				intent.putExtras(bundle);
	
	    				startActivity(intent);
	    				NoteListActivity.this.finish();
    				}
    			}
    		});
        }  
	}

	private void initUIData() {
		Bundle bundle = this.getIntent().getExtras();
		if (bundle == null) {
			noteType = ALL_NOTE_TYPE;
			mTitle.setText("所有笔记");
		} else {
			noteType = bundle.getInt("note_type");
			switch (noteType) {
			case ALL_NOTE_TYPE:
				mTitle.setText("所有笔记");
				break;
			case NOTEBOOK_TYPE:
				notebookGuid = bundle.getString("guid");
				NotebookService nbSrv = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
				mTitle.setText(nbSrv.getNotebook(notebookGuid).getName());
				break;
			case TAG_NOTE_TYPE:
				tagGuid = bundle.getString("guid");
				TagService tagSrv = (TagService)ApplicationContext.getSingleton().getBean("TagService");
				mTitle.setText(tagSrv.getTag(tagGuid).getName());
				break;
			case FAVORITE_TYPE:
				mTitle.setText("收藏");
				break;
			}
		}
		mNoteCount.setText(Integer.toString(100));
	}
	        
	private void doUpdate() {
		new GetNotesTask().execute("");
	}

	private class DelNotesTask extends AsyncTask<String, String, String> {
		public String doInBackground(String... params) {
			NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
			if (noteSrv != null) {
				for (String noteGuid : selectData) {
					noteSrv.deleteNote(noteGuid);
				}
				// 获取数据
				loadData(0, pageSize);
			}
			return "";
		}

		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_DELETE);
		}

		@Override
		public void onPostExecute(String Re) {
			removeDialog(DIALOG_DELETE);
			//通知适配器，发现改变操作
			updateAdapter();
			mNoteCount.setText(Integer.toString(listData.size()));
		}
						
	}
	
	private class GetNotesTask extends AsyncTask<String, String, String> {
		public String doInBackground(String... params) {		 
			// 获取数据
			loadData(0, pageSize);
			return "";
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		public void onPostExecute(String Re) {
			//绑定LISTVIEW
			if(listData.size()==0){
				//emptytextView.setVisibility(View.VISIBLE);
			}
			else{
				updateAdapter();
			}
			
						
			mNoteCount.setText(Integer.toString(listData.size()));
		}
	}

	// 加载数据
	private void loadData(int pageStart,int pageSize) {
		List<NoteModel> listNewNotes = null;
		if (Global.noteSrv != null) {
			switch (noteType) {
			case ALL_NOTE_TYPE:
				listNewNotes = Global.noteSrv.getActiveNotes();
				break;
			case NOTEBOOK_TYPE:
				listNewNotes = Global.noteSrv.getNotebookActiveNotes(notebookGuid);
				break;
			case TAG_NOTE_TYPE:
				listNewNotes = Global.noteSrv.getTagActiveNotes(tagGuid);
				break;
			case FAVORITE_TYPE:
				listNewNotes = Global.noteSrv.getActiveNotes();
				break;
			}
		}

		// 目前每次都是全部数据
		listData.clear();
		for (int i=0; i<listNewNotes.size(); ++i) {
			if (selectData.contains(listNewNotes.get(i).getGuid())) {
				listData.add(new Item(listNewNotes.get(i), true));
			} else {
				listData.add(new Item(listNewNotes.get(i), false));
			}
		}
		
		if (listData.size() != 0) {
			// 排序
			sortData();
		}
	}


	// 数据排序
	@SuppressWarnings("unchecked")
	private void sortData() {
		switch (noteSortType) {
		case NOTE_SORT_UPDATED:
			Collections.sort(listData, new NoteUpdatedTimeComparator());
			break;
		case NOTE_SORT_CREATE:
			Collections.sort(listData, new NoteCreateTimeComparator());  
			break;
		case NOTE_SORT_TITLE:
			Collections.sort(listData, new NoteTitleComparator());  
			break;
		default:
			Collections.sort(listData, new NoteUpdatedTimeComparator());
			break;
		}
	}

	// 按创建时间排序
	@SuppressWarnings("rawtypes")
	private class NoteCreateTimeComparator implements Comparator{ 
	    public int compare(Object o1,Object o2) { 
	    	Item c1=(Item)o1; 
	    	Item c2=(Item)o2; 
	    	
	    	return new Date(c2.note.getCreated()).compareTo(new Date(c1.note.getCreated()));
	    } 
	} 
	// 按创建时间排序
	@SuppressWarnings("rawtypes")
	private class NoteUpdatedTimeComparator implements Comparator{ 
	    public int compare(Object o1,Object o2) { 
	    	Item c1=(Item)o1; 
	    	Item c2=(Item)o2; 
	    	
	    	return new Date(c2.note.getUpdated()).compareTo(new Date(c1.note.getUpdated()));
	    } 
	} 
	// 按标题排序
	@SuppressWarnings("rawtypes")
	private class NoteTitleComparator implements Comparator{ 
	    public int compare(Object o1,Object o2) { 
	    	Item c1=(Item)o1; 
	    	Item c2=(Item)o2; 
	    	Collator myCollator = Collator.getInstance(java.util.Locale.CHINA);
	    	return myCollator.compare(c1.note.getTitle(), c2.note.getTitle());
	    } 
	} 

	// 数据分组
	private void orderData() {
		listDataCate.clear();
		orderData.clear();
		if (listData.size() != 0) {
	        Date lastDate = new Date(listData.get(0).note.getUpdated());
	        ArrayList<Item> cateNotes = new ArrayList<Item>();
	        cateNotes.add(listData.get(0));
	        
	        for (int i=1; i<listData.size(); ++i) {
	        	Date updatedDate = new Date(listData.get(i).note.getUpdated());
	        	if (Global.isSameMonth(lastDate, updatedDate)) {
	        		cateNotes.add(listData.get(i));
	        	} else {
	        		// 将之前月放入adapter中
	        		orderData.add(new Pair<String, ArrayList<Item>>(Global.DateMonthFormat(lastDate), cateNotes));
	        		lastDate = new Date(listData.get(i).note.getUpdated());
	        		cateNotes = new ArrayList<Item>();
	        		cateNotes.add(listData.get(i));
	        	}		        		
	        }
    		orderData.add(new Pair<String, ArrayList<Item>>(Global.DateMonthFormat(lastDate), cateNotes));
		}
	}
	
	//刷新适配器
	public void updateAdapter() {
		orderData();
		
		mCategoryAdapter.setData(orderData);
		

//		Set<Map.Entry<String, ArrayList<Item>>> set = listDataCate.entrySet();
//        for (Iterator<Map.Entry<String, ArrayList<Item>>> it = set.iterator(); it.hasNext();) {
//            Map.Entry<String, ArrayList<Item>> entry = (Map.Entry<String, ArrayList<Item>>) it.next();
//            
//    		if (isGridView) {
////    			mCategoryAdapter.addCategory(entry.getKey(), entry.getValue().size(), 
////    				new NoteGridAdapter(NoteListActivity.this, R.layout.list_child_item_note_grid, entry.getValue()));		        			
//    			mCategoryAdapter.addCategory(entry.getKey(), entry.getValue().size(), 
//    				new NoteGridAdapter(NoteListActivity.this, R.layout.list_grid_note, entry.getValue()));		        			
//    		} else {
//    			mCategoryAdapter.addCategory(entry.getKey(), entry.getValue().size(), 
//    				new NoteListAdapter(NoteListActivity.this, R.layout.list_child_item_note, entry.getValue()));
//    		}
//        }
		if (isEditable) {
			int size = listData.size();
			selectData.clear();
			for(int i=0;i<size;i++){
				if(listData.get(i).b)
					//count++;
					selectData.add(listData.get(i).note.getGuid());
				else
					selectData.remove(listData.get(i).note.getGuid());
			}			
		}
		mCategoryAdapter.notifyDataSetChanged();
		
	}
    


	public String getHtmlString(String urlString) {
	    try {
	        URL url = new URL(urlString);
	        URLConnection ucon = url.openConnection();
	        InputStream instr = ucon.getInputStream();
	        BufferedInputStream bis = new BufferedInputStream(instr);
	        ByteArrayBuffer baf = new ByteArrayBuffer(500);
	        int current = 0;
	        while ((current = bis.read()) != -1) {
	            baf.append((byte) current);
	        }
	        return EncodingUtils.getString(baf.toByteArray(), "utf-8");
	    } catch (Exception e) {
	        return "";
	    }
	}

	class Item{
		public NoteModel note;
		public boolean b = false;
		public Item(NoteModel note,boolean b){
			this.note = note;
			this.b = b;
		}
	}

	class SectionComposerAdapter extends SosUniversalAdapter {
		ArrayList<Pair<String, ArrayList<Item>>> all = new ArrayList<Pair<String, ArrayList<Item>>>();

		public void setData(ArrayList<Pair<String, ArrayList<Item>>> data) {
			all = data;			
		}
		

		class NoteViewHolder {
			public CheckBox note_cb = null;
			public ImageView note_favorite_iv = null;
			public TextView  note_title_tv = null;
			public TextView  note_time_tv = null;
			public TextView  note_content_tv = null;
			public ImageView note_image_iv = null;
		}

		public int getCount() {
			int res = 0;
			for (int i = 0; i < all.size(); i++) {
				res += all.get(i).second.size();
			}
			return res;
		}

		
		public Item getItem(int position) {
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (position >= c && position < c + all.get(i).second.size()) {
					return all.get(i).second.get(position - c);
				}
				c += all.get(i).second.size();
			}
			return null;
		}

		
		public long getItemId(int position) {
			return position;
		}

		
		protected void onNextPageRequested(int page) {
		}

		
		protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
			if (displaySectionHeader) {
				view.findViewById(R.id.list_note_title).setVisibility(View.VISIBLE);
				
    			TextView  title_tv = (TextView) view.findViewById(R.id.list_title_tv);
    			TextView  count_tv = (TextView) view.findViewById(R.id.list_count_tv);
    			//count_tv.setVisibility(View.GONE);
    			title_tv.setText(getSections()[getSectionForPosition(position)]);  
    			count_tv.setText(Integer.toString(all.get(getSectionForPosition(position)).second.size()));
			} else {
				view.findViewById(R.id.list_note_title).setVisibility(View.GONE);
			}
		}

		
		public View getAmazingView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			NoteViewHolder holder;
			if(view == null || (holder=(NoteViewHolder)view.getTag()) == null){
				holder = new NoteViewHolder();
				view = getLayoutInflater().inflate(R.layout.list_child_item_note, null);
				holder.note_cb = (CheckBox) view.findViewById(R.id.item_cb);
				holder.note_favorite_iv = (ImageView) view.findViewById(R.id.note_favorite_iv);
				holder.note_title_tv = (TextView) view.findViewById(R.id.note_title_tv);
				holder.note_time_tv = (TextView) view.findViewById(R.id.note_time_tv);
				holder.note_content_tv = (TextView) view.findViewById(R.id.note_content_tv);
				holder.note_image_iv = (ImageView) view.findViewById(R.id.note_image_iv);
				view.setTag(holder);
			}
			if (isEditable) {
				holder.note_cb.setVisibility(View.VISIBLE);
				holder.note_cb.setChecked(getItem(position).b);
			} else {
				holder.note_cb.setVisibility(View.GONE);
			}

			// TODO
			holder.note_favorite_iv.setVisibility(View.GONE);
			final NoteModel newNote = getItem(position).note;
			if (newNote != null) {
				holder.note_title_tv.setText(newNote.getTitle());
				if (newNote.getUpdated() != 0) {
					holder.note_time_tv.setText(Global.DateFormat(newNote.getUpdated(), false));
				}

				Document document = Jsoup.parse(newNote.getContent());
				holder.note_content_tv.setText(document.body().getElementsByTag("p").text());
				
				Elements elems = document.body().getElementsByTag("img");
				final String guid = Global.getFileNameNoEx(elems.attr("src"));

				if (StringUtils.isNull(guid)) {
					holder.note_image_iv.setVisibility(View.GONE);
				} else {
					// 异步加载图片
					holder.note_image_iv.setTag(guid);
					Drawable cachedImage = Global.asyncImageLoader.loadDrawable(guid, 150, 150, new ImageCallback() {
	
						@Override
						public void imageLoaded(Drawable imageDrawable, String imageUrl) {
							ImageView imageViewByTag = (ImageView)mDisplay.findViewWithTag(guid);
							if (imageViewByTag != null) {
								imageViewByTag.setImageDrawable(imageDrawable);
							}						
						}					
					});
					if (cachedImage == null) {
						holder.note_image_iv.setImageResource(R.drawable.ic_menu_sync);
					} else {
						holder.note_image_iv.setImageDrawable(cachedImage);
					}
				}
			}
			
			return view;			
		}

		
		public void configurePinnedHeader(View header, int position, int alpha) {
			if (header != null) {
				TextView  title_tv = (TextView) header.findViewById(R.id.list_title_tv);
				TextView  count_tv = (TextView) header.findViewById(R.id.list_count_tv);
	
				title_tv.setText(getSections()[getSectionForPosition(position)]);
				count_tv.setText(Integer.toString(all.get(getSectionForPosition(position)).second.size()));
			}
		}

		
		public int getPositionForSection(int section) {
			if (section < 0) section = 0;
			if (section >= all.size()) section = all.size() - 1;
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (section == i) { 
					return c;
				}
				c += all.get(i).second.size();
			}
			return 0;
		}

		public int getSectionForPosition(int position) {
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (position >= c && position < c + all.get(i).second.size()) {
					return i;
				}
				c += all.get(i).second.size();
			}
			return -1;
		}

		public String[] getSections() {
			String[] res = new String[all.size()];
			for (int i = 0; i < all.size(); i++) {
				res[i] = all.get(i).first;
			}
			return res;
		}
		
	}

}
